package com.lyl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lyl.common.BaseContext;
import com.lyl.common.R;
import com.lyl.entity.AddressBook;
import com.lyl.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 李亚龙
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;


    /**
     * 保存用户地址信息
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        //增添属性，用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("保存地址信息：{}",addressBook);
        addressBookService.save(addressBook);
        return R.success("地址保存成功");
    }

    /**
     * 获取用户全部地址信息
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        //获取当前用户的id
        Long currentUserId = BaseContext.getCurrentId();
        log.info("获取用户 {} 全部地址信息",currentUserId);
        //构造条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,currentUserId);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }


    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        log.info("设置地址id为：{} 成为默认地址",addressBook.getId());
        //首先将该用户的全部地址的is_default设置为0
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(AddressBook::getIsDefault,0);
        updateWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        addressBookService.update(updateWrapper);

        //然后再精确将指定id的地址设置为默认地址
        addressBook.setIsDefault(1);
        log.info("设置地址{}",addressBook);
        addressBookService.updateById(addressBook);

        return R.success(addressBook);
    }

    /**
     * 根据用户id获取默认地址
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        log.info("获取默认地址");
        Long currentUserId = BaseContext.getCurrentId();
        //根据用户id查询，默认地址
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,currentUserId);
        queryWrapper.eq(AddressBook::getIsDefault,1);

        AddressBook addressBook = addressBookService.getOne(queryWrapper);

        return R.success(addressBook);
    }

}
